<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showdailog=true;isAdd=true">添加角色</el-button>
      </div>
      <el-table :data="list">
        <el-table-column
          align="center"
          width="200"
          label="角色"
          prop="name"
        ><template v-slot="{row}">
          <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
          <span v-else>{{ row.name }}</span>
        </template></el-table-column>
        <el-table-column
          align="center"
          label="启用"
          width="200"
          prop="state"
        >
          <template
            v-slot="{row}"
          >
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state==1?"已启用":(row.state==0?"未启用":'无') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="
            center"
          label="描述"
          prop="description"
        >
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template></el-table-column>
        <el-table-column
          align="center"
          label="操作"
        >
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="btnEditOK(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button v-if="hasPerm('edit-role')" size="mini" type="text" @click="btnEditRow(row)">编辑 </el-button>
              <el-popconfirm v-if="hasPerm('del-role')" title="确定删除吗" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" size="mini" type="text"> 删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" align="middle" style="height:60px ">
        <el-pagination
          layout="prev, pager, next"
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          @current-change="changePage"
        /></el-row>
    </div>
    <el-dialog :title="isAdd?'新增角色':'编辑角色'" :visible.sync="showdailog" width="500px" @close="btnCancel">
      <el-form ref="roleForm" label-width="120px" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称 " prop="name">
          <el-input v-model="roleForm.name" size="mini" style="width:300px" />

        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="roleForm.state" size="mini" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" size="mini" type="textarea" :rows="3" style="width:300px" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :visible.sync="showddailog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree
        ref="permTree"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showddailog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, getRole, updataRole, deleteRole, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Role',
  data() {
    return {
      permIds: [],
      currentRoleId: null,
      permissionData: [],
      showddailog: false,
      list: [],
      isAdd: true,
      // isEdit: false,
      pageParams: {
        total: 0,
        page: 1,
        pagesize: 5
      },
      showdailog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      }

    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      this.pageParams.total = total
      this.list.forEach(item => this.$set(item, 'isEdit', false))
      this.list.forEach(item => this.$set(item, 'editRow', {
        name: item.name,
        description: item.description,
        state: item.state

      }))
      // console.log(rows, total
      // )
      // console.log(this.pageParams)
    },
    changePage(newpage) {
      this.pageParams.page = newpage
      this.getRoleList()
      // console.log(newpage)
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOk => {
        if (isOk) {
          if (this.isAdd) {
            await addRole(this.roleForm)
            // console.log(this.roleForm)
            this.$message.success('新增角色成功')
          } else {
            await updataRole(this.roleForm.id, this.roleForm)
            this.$message.success('编辑角色成功')
          }
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.roleForm = this.$options.data().roleForm
      this.$refs.roleForm.resetFields()
      this.showdailog = false
    },
    async showEdit(id) {
      const data = await getRole(id)
      console.log(data)
      this.roleForm = data
      this.isAdd = false
      this.showdailog = true
    },
    btnEditRow(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
    },
    async btnEditOK(row) {
      if (row.editRow.description && row.editRow.name) {
        await updataRole({ ...row.editRow, id: row.id })
        this.$message.success('更新角色成功')
        Object.assign(row, row.editRow)
        // eslint-disable-next-line require-atomic-updates
        row.isEdit = false
      } else {
        this.$message.warning('描述角色为空')
      }
    },
    async confirmDel(id) {
      await deleteRole(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showddailog = true
    },
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showddailog = false
    }

  }

}
</script>
<style scoped>
.role-operate {
  padding: 10px;

}
</style>
